import configService from './config.service';
// import store from '../store'

async function request(options) {
  //header处理
  options.header = options.header || {};
  options.header = Object.assign(
    { 'Content-Type': 'application/json; charset=UTF-8' },
    options.header,
  );

  //token处理
  options.header['X-Access-Token'] = uni.getStorageSync('X-Access-Token') || '';

  //url处理
  let url = configService.apiUrl + options.url;

  //这个是否显示遮罩
  let loadingTimer = null;
  if (options.showLoading) {
    loadingTimer = setTimeout(() => {
      uni.showLoading({
        title: '加载中',
      });
    }, 500);
  }
  //处理一下data对象里的数据，方便Dict实例使用

  for (let key in options.data) {
    if (
      options.data[key] !== null &&
      options.data[key] != undefined &&
      options.data[key].getValue
    ) {
      options.data[key] = options.data[key].getValue();
    }
  }

  return new Promise((resolve, reject) => {
    uni.request({
      url: url,
      method: options.method || 'get',
      data: options.data || {},
      header: options.header,
      success: function (res) {
        if (options.showLoading) {
          uni.hideLoading();
          clearTimeout(loadingTimer);
          loadingTimer = null;
        }
        if (
          res.data.code === '200' ||
          res.data.code == 0 ||
          res.data.status == '1' ||
          res.data.status == 0
        ) {
          resolve(res);
        } else if (res.data.code == '401') {
          uni.reLaunch({
            url: '../login/login',
          });
        } else {
          if (res.data.code == '6017' || res.data.code == '9103') {
            uni.getStorageSync('X-Access-Token');
            resolve(res);
          } else {
            resolve(res);
          }
        }
      },
      fail: function (err) {
        if (options.showLoading) {
          uni.hideLoading();
          clearTimeout(loadingTimer);
          loadingTimer = null;
        }
        //错误统一处理，弹窗显示
        if (!options.isBanToastErr) {
          let errmsg = '网络繁忙，请联系系统管理员。';
          if (err.message) {
            errmsg = err.message;
          } else if (err.statusCode) {
            errmsg = `error status code : ${err.statusCode}`;
          }
          uni.showToast({
            title: errmsg,
            icon: 'none',
          });
        }
        reject(err);
      },
    });
  }).then(async (res) => {
    // let token = res.result.token || res.result.token
    // if (token) {
    //     uni.getStorageSync('X-Access-Token', token)
    // }
    // if (res.data) {
    //   return res.data
    // } else {
    return res
    // }
  });
}
async function uploadFile(options) {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: configService.apiUrl + options.url,
      filePath: options.files,
      header: { ['X-Access-Token']: uni.getStorageSync('X-Access-Token') },
      name: 'files',
      // formData: options.data,
      success: function (res) {
        var data = JSON.parse(res.data);
        resolve(data)
      },
      fail: function (e) {
        uni.showToast({
          title: e.showToast || '上传文件失败',
          icon: 'none',
        });
        resolve(e);
      },
    });
  });
}
uni.$ylRequest = request;
uni.$ylUpload = uploadFile;
